<template>
  <div class="flex h-[calc(100vh-100px)] relative">
    <!-- 左侧树形控件 -->
    <transition name="fade">
      <div v-if="showTree" class="tree-container relative">
        <TypeTree
          :type-info="{ type: 1, typeName: '项目类型' }"
          @node-click="handleTreeNodeClick"
          @refresh-material-class="refreshList"
        />
        <!-- 折叠按钮，贴在树的右侧 -->
        <el-button :icon="CaretLeft" class="collapse-btn" @click="showTree = false" />
      </div>
    </transition>
    <!-- 展开按钮，树隐藏时显示，悬浮在左侧 -->
    <el-button v-if="!showTree" :icon="CaretRight" class="expand-btn" @click="showTree = true" />
    <!-- 右侧内容区 -->
    <div class="flex-1 overflow-hidden pl-4 flex flex-col">
      <!-- 固定头部区域 -->
      <div class="mb-4">
        <ContentWrap>
          <!-- 状态分类 Tabs -->
          <el-tabs v-model="queryParams.status" @tab-change="handleTabChange">
            <el-tab-pane  label="全部" name="">
              <template #label>
                全部
                <el-tag v-if="statusCount['0']" class="ml-2" round size="small" type="info">
                  ({{ statusCount['0'] }})
                </el-tag>
              </template>
            </el-tab-pane>
            <el-tab-pane v-if="tabRangeArr.includes(1)"   name="10">
              <template #label>
                待分配
                <el-tag v-if="statusCount['1']" class="ml-2" round size="small" type="info">
                  ({{ statusCount['10'] }})
                </el-tag>
              </template>
            </el-tab-pane>
            <el-tab-pane v-if="tabRangeArr.includes(2)"  name="20">
              <template #label>
                待调查
                <el-tag v-if="statusCount['20']" class="ml-2" round size="small" type="info">
                  ({{ statusCount['20'] }})
                </el-tag>
              </template>
            </el-tab-pane>
            <el-tab-pane v-if="tabRangeArr.includes(3)"  name="30">
              <template #label>
                调查中
                <el-tag v-if="statusCount['30']" class="ml-2" round size="small" type="info">
                  ({{ statusCount['30'] }})
                </el-tag>
              </template>
            </el-tab-pane>
            <el-tab-pane v-if="tabRangeArr.includes(4)"   name="31">
              <template #label>
                定性采样
                <el-tag v-if="statusCount['31']" class="ml-2" round size="small" type="info">
                  ({{ statusCount['31'] }})
                </el-tag>
              </template>
            </el-tab-pane>
            <el-tab-pane v-if="tabRangeArr.includes(5)"   name="32">
              <template #label>
                定性流转
                <el-tag v-if="statusCount['32']" class="ml-2" round size="small" type="info">
                  ({{ statusCount['32'] }})
                </el-tag>
              </template>
            </el-tab-pane>
            <el-tab-pane v-if="tabRangeArr.includes(6)"   name="33">
              <template #label>
                定性已传
                <el-tag v-if="statusCount['33']" class="ml-2" round size="small" type="info">
                  ({{ statusCount['33'] }})
                </el-tag>
              </template>
            </el-tab-pane>
            <el-tab-pane v-if="tabRangeArr.includes(7)"   name="34">
              <template #label>
                定性完成
                <el-tag v-if="statusCount['34']" class="ml-2" round size="small" type="info">
                  ({{ statusCount['34'] }})
                </el-tag>
              </template>
            </el-tab-pane>
            <el-tab-pane v-if="tabRangeArr.includes(8)"   name="35">
              <template #label>
                调查完成
                <el-tag v-if="statusCount['35']" class="ml-2" round size="small" type="info">
                  ({{ statusCount['35'] }})
                </el-tag>
              </template>
            </el-tab-pane>
            <el-tab-pane v-if="tabRangeArr.includes(9)"   name="40">
              <template #label>
                方案完成
                <el-tag v-if="statusCount['40']" class="ml-2" round size="small" type="info">
                  ({{ statusCount['40'] }})
                </el-tag>
              </template>
            </el-tab-pane>
            <el-tab-pane v-if="tabRangeArr.includes(10)"   name="50">
              <template #label>
                方案审核
                <el-tag v-if="statusCount['50']" class="ml-2" round size="small" type="info">
                  ({{ statusCount['50'] }})
                </el-tag>
              </template>
            </el-tab-pane>
            <el-tab-pane v-if="tabRangeArr.includes(11)"   name="60">
              <template #label>
                采样分配
                <el-tag v-if="statusCount['60']" class="ml-2" round size="small" type="info">
                  ({{ statusCount['60'] }})
                </el-tag>
              </template>
            </el-tab-pane>
            <el-tab-pane v-if="tabRangeArr.includes(12)"   name="70">
              <template #label>
                设备领用
                <el-tag v-if="statusCount['70']" class="ml-2" round size="small" type="info">
                  ({{ statusCount['70'] }})
                </el-tag>
              </template>
            </el-tab-pane>
            <el-tab-pane v-if="tabRangeArr.includes(13)"   name="80">
              <template #label>
                耗材领用
                <el-tag v-if="statusCount['80']" class="ml-2" round size="small" type="info">
                  ({{ statusCount['80'] }})
                </el-tag>
              </template>
            </el-tab-pane>
            <el-tab-pane v-if="tabRangeArr.includes(14)"   name="90">
              <template #label>
                采样前滤膜
                <el-tag v-if="statusCount['90']" class="ml-2" round size="small" type="info">
                  ({{ statusCount['90'] }})
                </el-tag>
              </template>
            </el-tab-pane>
            <el-tab-pane v-if="tabRangeArr.includes(15)"   name="100">
              <template #label>
                现场采样
                <el-tag v-if="statusCount['100']" class="ml-2" round size="small" type="info">
                  ({{ statusCount['100'] }})
                </el-tag>
              </template>
            </el-tab-pane>
<!--            <el-tab-pane v-if="tabRangeArr.includes(15)"   name="9">-->
<!--              <template #label>-->
<!--                实验中-->
<!--                <el-tag v-if="statusCount['9']" class="ml-2" round size="small" type="info">-->
<!--                  ({{ statusCount['9'] }})-->
<!--                </el-tag>-->
<!--              </template>-->
<!--            </el-tab-pane>-->
<!--            <el-tab-pane v-if="tabRangeArr.includes(16)"   name="10">-->
<!--              <template #label>-->
<!--                待分配编辑-->
<!--                <el-tag v-if="statusCount['10']" class="ml-2" round size="small" type="info">-->
<!--                  ({{ statusCount['10'] }})-->
<!--                </el-tag>-->
<!--              </template>-->
<!--            </el-tab-pane>-->
<!--            <el-tab-pane v-if="tabRangeArr.includes(17)"   name="11">-->
<!--              <template #label>-->
<!--                报告编辑中-->
<!--                <el-tag v-if="statusCount['11']" class="ml-2" round size="small" type="info">-->
<!--                  ({{ statusCount['11'] }})-->
<!--                </el-tag>-->
<!--              </template>-->
<!--            </el-tab-pane>-->
<!--            <el-tab-pane v-if="tabRangeArr.includes(18)"   name="12">-->
<!--              <template #label>-->
<!--                待发放报告-->
<!--                <el-tag v-if="statusCount['12']" class="ml-2" round size="small" type="info">-->
<!--                  ({{ statusCount['12'] }})-->
<!--                </el-tag>-->
<!--              </template>-->
<!--            </el-tab-pane>-->
<!--            <el-tab-pane v-if="tabRangeArr.includes(19)"   name="13">-->
<!--              <template #label>-->
<!--                归档中-->
<!--                <el-tag v-if="statusCount['13']" class="ml-2" round size="small" type="info">-->
<!--                  ({{ statusCount['13'] }})-->
<!--                </el-tag>-->
<!--              </template>-->
<!--            </el-tab-pane>-->
<!--            <el-tab-pane v-if="tabRangeArr.includes(20)"   name="14">-->
<!--              <template #label>-->
<!--                已完成-->
<!--                <el-tag v-if="statusCount['14']" class="ml-2" round size="small" type="info">-->
<!--                  ({{ statusCount['14'] }})-->
<!--                </el-tag>-->
<!--              </template>-->
<!--            </el-tab-pane>-->
          </el-tabs>

          <!-- 搜索工作栏 -->
          <el-form
            ref="queryFormRef"
            :inline="true"
            :model="queryParams"
            class="-mb-15px"
            label-width="68px"
          >
            <el-form-item label="委托单位" prop="companyName">
              <el-input
                v-model="queryParams.companyName"
                class="!w-240px"
                clearable
                placeholder="请输入委托单位名称"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime">
              <el-date-picker
                v-model="queryParams.createTime"
                :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
                class="!w-220px"
                end-placeholder="结束日期"
                start-placeholder="开始日期"
                type="daterange"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item>
              <el-button @click="handleQuery">
                <Icon class="mr-5px" icon="ep:search" />
                搜索
              </el-button>
              <el-button @click="resetQuery">
                <Icon class="mr-5px" icon="ep:refresh" />
                重置
              </el-button>
              <el-button
                v-hasPermi="['dk:project:addproject']"
                link
                type="primary"
                @click="openForm('create')"
              >
                <Icon class="mr-5px" icon="ep:plus" />
                新增
              </el-button>
              <el-button
                v-hasPermi="['dk:project:excel']"
                :loading="exportLoading"
                link
                type="success"
                @click="handleExport"
              >
                <Icon class="mr-5px" icon="ep:download" />
                导出
              </el-button>
            </el-form-item>
          </el-form>
        </ContentWrap>
      </div>

      <!-- 可滚动的列表区域 -->
      <el-scrollbar class="flex-1">
        <ContentWrap class="h-full flex flex-col">
          <el-table
            v-loading="loading"
            :data="list"
            :expand-row-keys="expandRowKeys"
            :show-overflow-tooltip="true"
            :stripe="true"
            class="flex-1"
            row-key="id"
            @row-click="handleRowClick"
          >
            <el-table-column type="expand">
              <template #default="scope">
                <div class="expand-buttons p-4">
                  <el-button
                    v-hasPermi="['dk:project:dcfp', 'dk:myproject:dcfp','dk:tobesurvery:dcfp', 'dk:mysurvey:dcfp','dk:allsample:dcfp', 'dk:mysample:dcfp']"
                    link
                    type="primary"
                    :class="{ 'current-status-button': isCurrentStatusButton('调查分配', scope.row.status) }"
                    @click.stop="openAssignForm(scope.row, 'survey')"
                  >
                    调查分配
                  </el-button>
                  <el-button
                    v-hasPermi="['dk:project:xcdc', 'dk:myproject:xcdc','dk:tobesurvery:xcdc', 'dk:mysurvey:xcdc','dk:allsample:xcdc', 'dk:mysample:xcdc']"
                    link
                    type="primary"
                    :class="{ 'current-status-button': isCurrentStatusButton('现场调查', scope.row.status) }"
                    @click.stop="toPage(scope.row, '/survey/fieldSurvey', 20)"
                  >
                    现场调查
                  </el-button>
                  <el-button
                    v-hasPermi="['dk:project:dxcy', 'dk:myproject:dxcy','dk:tobesurvery:dxcy', 'dk:mysurvey:dxcy','dk:allsample:dxcy', 'dk:mysample:dxcy']"
                    link
                    type="primary"
                    :class="{ 'current-status-button': isCurrentStatusButton('定性采样', scope.row.status) }"
                    @click.stop="toPage(scope.row, '/survey/unknownAnalysisSampling', 30)"
                  >
                    定性采样
                  </el-button>
                  <el-button
                    v-hasPermi="['dk:project:dxlz', 'dk:myproject:dxlz','dk:tobesurvery:dxlz', 'dk:mysurvey:dxlz','dk:allsample:dxlz', 'dk:mysample:dxlz']"
                    link
                    type="primary"
                    :class="{ 'current-status-button': isCurrentStatusButton('定性流转', scope.row.status) }"
                    @click.stop="toPage(scope.row, '/survey/unknownAnalysisTransfer', 31)"
                  >
                    定性流转
                  </el-button>
                  <el-button
                    v-hasPermi="['dk:project:dxjg', 'dk:myproject:dxjg','dk:tobesurvery:dxjg', 'dk:mysurvey:dxjg','dk:allsample:dxjg', 'dk:mysample:dxjg']"
                    link
                    type="primary"
                    :class="{ 'current-status-button': isCurrentStatusButton('定性结果', scope.row.status) }"
                    @click.stop="toPage(scope.row, '/survey/unknownAnalysisResult', 32)"
                  >
                    定性结果
                  </el-button>
                  <el-button
                    v-hasPermi="['dk:project:dxwc', 'dk:myproject:dxwc','dk:tobesurvery:dxwc', 'dk:mysurvey:dxwc','dk:allsample:dxwc', 'dk:mysample:dxwc']"
                    link
                    type="primary"
                    :class="{ 'current-status-button': isCurrentStatusButton('定性完成', scope.row.status) }"
                    @click.stop="toPage(scope.row, '/survey/qualitativeCompletion', 33)"
                  >
                    定性完成
                  </el-button>
                  <el-button
                    v-hasPermi="['dk:project:dcwc', 'dk:myproject:dcwc','dk:tobesurvery:dcwc', 'dk:mysurvey:dcwc','dk:allsample:dcwc', 'dk:mysample:dcwc']"
                    link
                    type="primary"
                    :class="{ 'current-status-button': isCurrentStatusButton('调查完成', scope.row.status) }"
                    @click.stop="toPage(scope.row, '/survey/qualitativeCompletion', 34)"
                  >
                    调查完成
                  </el-button>
                  <el-button
                    v-hasPermi="['dk:project:cyfa', 'dk:myproject:cyfa','dk:tobesurvery:cyfa', 'dk:mysurvey:cyfa','dk:allsample:cyfa', 'dk:mysample:cyfa']"
                    link
                    type="primary"
                    :class="{ 'current-status-button': isCurrentStatusButton('采样方案', scope.row.status) }"
                    @click.stop="toPage(scope.row, '/survey/jobSurvey', 35)"
                  >
                    采样方案
                  </el-button>
                  <el-button
                    v-hasPermi="['dk:project:fash', 'dk:myproject:fash','dk:tobesurvery:fash', 'dk:mysurvey:fash','dk:allsample:fash', 'dk:mysample:fash']"
                    link
                    type="primary"
                    :class="{ 'current-status-button': isCurrentStatusButton('方案审核', scope.row.status) }"
                    @click.stop="toPage(scope.row, '/survey/planReviewDialog', 40)"
                  >
                    方案审核
                  </el-button>
                  <el-button
                    v-hasPermi="['dk:project:cyfp', 'dk:myproject:cyfp','dk:tobesurvery:cyfp', 'dk:mysurvey:cyfp','dk:allsample:cyfp', 'dk:mysample:cyfp']"
                    link
                    type="primary"
                    :class="{ 'current-status-button': isCurrentStatusButton('采样分配', scope.row.status) }"
                    @click.stop="openSamplingForm(scope.row, 'sample')"
                  >
                    采样分配
                  </el-button>
                  <el-button
                    v-hasPermi="['dk:project:sbly', 'dk:myproject:sbly','dk:tobesurvery:sbly', 'dk:mysurvey:sbly','dk:allsample:sbly', 'dk:mysample:sbly']"
                    link
                    type="primary"
                    :class="{ 'current-status-button': isCurrentStatusButton('设备领用', scope.row.status) }"
                    @click.stop="toPage(scope.row, '/sample/equipmentcollection', 60)"
                  >
                    设备领用
                  </el-button>
                  <el-button
                    v-hasPermi="['dk:project:hcly', 'dk:myproject:hcly','dk:tobesurvery:hcly', 'dk:mysurvey:hcly','dk:allsample:hcly', 'dk:mysample:hcly']"
                    link
                    type="primary"
                    :class="{ 'current-status-button': isCurrentStatusButton('耗材领用', scope.row.status) }"
                    @click.stop="toPage(scope.row, '/sample/consumable', 60)"
                  >
                    耗材领用
                  </el-button>
                  <el-button
                    v-hasPermi="['dk:project:lmcyq', 'dk:myproject:lmcyq','dk:tobesurvery:lmcyq', 'dk:mysurvey:lmcyq','dk:allsample:lmcyq', 'dk:mysample:lmcyq']"
                    link
                    type="primary"
                    :class="{ 'current-status-button': isCurrentStatusButton('采样前滤膜', scope.row.status) }"
                    @click.stop="toPage(scope.row, '/survey/beforeSample', 60)"
                  >
                    采样前滤膜
                  </el-button>
                  <el-button
                    v-hasPermi="['dk:project:xccy', 'dk:myproject:xccy','dk:tobesurvery:xccy', 'dk:mysurvey:xccy','dk:allsample:xccy', 'dk:mysample:xccy']"
                    link
                    type="primary"
                    :class="{ 'current-status-button': isCurrentStatusButton('现场采样', scope.row.status) }"
                    @click.stop="toPage(scope.row, '/survey/harmfulFactorsIndex', 60)"
                  >
                    现场采样
                  </el-button>
                  <el-button
                    v-hasPermi="['dk:project:yplz', 'dk:myproject:yplz','dk:tobesurvery:yplz', 'dk:mysurvey:yplz','dk:allsample:yplz', 'dk:mysample:yplz']"
                    link
                    type="primary"
                    :class="{ 'current-status-button': isCurrentStatusButton('样品流转', scope.row.status) }"
                    @click.stop="toPage(scope.row, '/survey/sampleHandoverIndex', 0)"
                  >
                    样品流转
                  </el-button>
                  <el-button
                    v-hasPermi="['dk:project:lmcyh', 'dk:myproject:lmcyh','dk:tobesurvery:lmcyh', 'dk:mysurvey:lmcyh','dk:allsample:lmcyh', 'dk:mysample:lmcyh']"
                    link
                    type="primary"
                    :class="{ 'current-status-button': isCurrentStatusButton('采样后滤膜', scope.row.status) }"
                    @click.stop="toPage(scope.row, '/survey/afterSample', 0)"
                  >
                    采样后滤膜
                  </el-button>
                  <el-button
                    v-hasPermi="['dk:project:jgjs', 'dk:myproject:jgjs','dk:tobesurvery:jgjs', 'dk:mysurvey:jgjs','dk:allsample:jgjs', 'dk:mysample:jgjs']"
                    link
                    type="primary"
                    :class="{ 'current-status-button': isCurrentStatusButton('结果计算', scope.row.status) }"
                    @click.stop="toPage(scope.row, '/survey/resultCalculation', 0)"
                  >
                    结果计算
                  </el-button>
                  <el-button
                    v-hasPermi="['dk:project:ssbg', 'dk:myproject:ssbg','dk:tobesurvery:ssbg', 'dk:mysurvey:ssbg','dk:allsample:ssbg', 'dk:mysample:ssbg']"
                    link
                    type="primary"
                    :class="{ 'current-status-button': isCurrentStatusButton('实验报告', scope.row.status) }"
                    @click.stop="toPage(scope.row, '/survey/testReportIndex', 0)"
                  >
                    实验报告
                  </el-button>

                  <el-button
                    v-hasPermi="['dk:project:wjyl', 'dk:myproject:wjyl','dk:tobesurvery:wjyl', 'dk:mysurvey:wjyl','dk:allsample:wjyl', 'dk:mysample:wjyl']"
                    link
                    type="primary"
                    :class="{ 'current-status-button': isCurrentStatusButton('文件预览', scope.row.status) }"
                    @click.stop="toPage(scope.row, '/previewFile', 0)"
                  >
                    文件预览
                  </el-button>
                  <el-button
                    v-hasPermi="['dk:project:update', 'dk:myproject:update','dk:tobesurvery:update', 'dk:mysurvey:update','dk:allsample:update', 'dk:mysample:update']"
                    link
                    type="primary"
                    :class="{ 'current-status-button': isCurrentStatusButton('编辑', scope.row.status) }"
                    @click.stop="openForm('update', scope.row.id)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    v-hasPermi="['dk:project:delete', 'dk:myproject:delete','dk:tobesurvery:delete', 'dk:mysurvey:delete','dk:allsample:delete', 'dk:mysample:delete']"
                    link
                    type="danger"
                    :class="{ 'current-status-button': isCurrentStatusButton('删除', scope.row.status) }"
                    @click.stop="handleDelete(scope.row.id)"
                  >
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="序号" type="index" width="60" />
            <el-table-column align="center" label="项目编号" prop="projectNo" />
            <el-table-column align="center" label="状态" prop="status">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.PROJECT_STATUS" :value="scope.row.status" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="受检单位" prop="receivingUnit" />
            <el-table-column align="center" label="委托单位" prop="companyName" />
            <el-table-column align="center" label="紧急程度" prop="urgencyLevel">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.URGENCY_DEGREE" :value="scope.row.urgencyLevel" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="项目类型" prop="projectType" />
            <el-table-column align="center" label="项目负责人" prop="projectManager" />
            <el-table-column
              :formatter="dateFormatter"
              align="center"
              label="创建时间"
              prop="createTime"
              show-overflow-tooltip
              width="180px"
            />
          </el-table>

          <!-- 分页 -->
          <div class="mt-4">
            <Pagination
              v-model:limit="queryParams.pageSize"
              v-model:page="queryParams.pageNo"
              :total="total"
              @pagination="getList"
            />
          </div>
        </ContentWrap>
      </el-scrollbar>

      <!-- 表单弹窗：添加/修改 -->
      <ProjectForm ref="formRef" @success="getList" />
      <AssignForm ref="assignFormRef" @success="getList" />
      <SyncResultsDialog
        v-model="syncResultsDialogVisible"
        :project-id="projectId"
        :job-survey-ref="jobSurveyRef"
        @sync-completed="handleSyncCompleted"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { ProjectApi, ProjectVO } from '@/api/dk/project'
import ProjectForm from './ProjectForm.vue'
import AssignForm from './AssignForm.vue'
import { onMounted, reactive, ref } from 'vue'
import TypeTree from './TypeTree.vue'
import { useRoute, useRouter } from 'vue-router'
import { CaretLeft, CaretRight } from '@element-plus/icons-vue'
import SyncResultsDialog from '@/views/survey/SyncResultsDialog.vue'

/** 项目 列表 */
defineOptions({ name: 'ProjectList' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const router = useRouter()
const route = useRoute()
const loading = ref(false) // 列表的加载中
const isMy = ref(false) // 列表的加载中
const isAll = ref(false) // 列表的加载中
const list = ref<ProjectVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
// 是否存在可同步的定性结果
const hasUnknownResults = ref(false)
const jobSurveyRef = ref()
const projectId = ref('')
// 同步定性结果弹窗
const syncResultsDialogVisible = ref(false)
// 处理同步完成事件
const handleSyncCompleted = () => {
  // 同步完成后清除提示
  hasUnknownResults.value = false
}
const showTree = ref(false)
const mysurvey = ref('')
const dataRange = ref('')
const tabRangeArr = ref<number[]>([])

// 创建 tabRangeArr 到 status 的映射关系
const tabToStatusMapping = {
  1: 10,
  2: 20,
  3: 30,
  4: 31,
  5: 32,
  6: 33,
  7: 34,
  8: 35,
  9: 40,
  10: 50,
  11: 60,
  12: 70,
  13: 80,
  14: 90,
  15: 100,
  16: 110,
  17: 120,
}

// 状态和操作按钮的映射关系
const statusToButtonMapping = {
  20: '调查分配',
  30: '现场调查',
  31: '定性采样',
  32: '定性流转',
  33: '定性结果',
  34: '定性完成',
  35: '调查完成',
  40: '采样方案',
  50: '方案审核',
  60: '采样分配',
  70: '设备领用',
  80: '耗材领用',
  90: '采样前滤膜',
  100: '现场采样',
  110: '采样后滤膜',
  120: '样品流转',
  130: '结果计算',
  140: '实验报告'
}

// 将 tabRangeArr 转换为 status 集合
const getStatusArray = () => {
  const getStatusArray= tabRangeArr.value.map(tab => tabToStatusMapping[tab]).filter(status => status !== undefined)
  console.log( 'getStatusArray', getStatusArray)
  return getStatusArray;
}

// 检查按钮是否为当前状态对应的按钮
const isCurrentStatusButton = (buttonText: string, rowStatus: number) => {
  const currentStatusButton = statusToButtonMapping[rowStatus]
  return currentStatusButton === buttonText
}

// 修改 queryParams 的类型定义
interface QueryParams {
  pageNo: number
  pageSize: number
  companyName?: string
  projectType?: string
  projectManager?: string
  urgencyLevel?: string
  completionDate?: string[]
  receivingUnit?: string
  receivingAddress?: string
  contactPerson?: string
  contactPhone?: string
  taskSource?: string
  contractNumber?: string
  projectNo?: string
  projectName?: string
  businessPerson?: string
  businessPhone?: string
  status?: string
  contractDate?: string[]
  remarks?: string
  createTime?: string[]
  materialClassId?: number
}

const queryParams = reactive<QueryParams>({
  pageNo: 1,
  pageSize: 30,
  companyName: undefined,
  projectType: undefined,
  projectManager: undefined,
  urgencyLevel: undefined,
  completionDate: [],
  receivingUnit: undefined,
  receivingAddress: undefined,
  contactPerson: undefined,
  contactPhone: undefined,
  taskSource: undefined,
  contractNumber: undefined,
  projectNo: undefined,
  projectName: undefined,
  businessPerson: undefined,
  businessPhone: undefined,
  status: undefined,
  contractDate: [],
  remarks: undefined,
  createTime: [],
  materialClassId: undefined
})


const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const statusCount = ref<Record<string, number>>({}) // 状态统计数据

/** 获取状态统计 */
const getStatusCount = async () => {
  try {
    const data = await ProjectApi.getStatusCount({
      status: getStatusArray(), // 传递 status 集合
      materialClassId: queryParams.materialClassId // 传递节点ID
    })
    statusCount.value = data
  } catch (error) {
    console.error('获取状态统计失败:', error)
  }
}
const getMyStatusCount = async () => {
  try {
    const data = await ProjectApi.getMyStatusCount({
      status: getStatusArray(), // 传递 status 集合
      mysurvey: mysurvey.value, // 传递 status 集合
      materialClassId: queryParams.materialClassId // 传递节点ID
    })
    statusCount.value = data
  } catch (error) {
    console.error('获取状态统计失败:', error)
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  // 获取 status 集合
  const statusArray = getStatusArray()
  console.log('传递的 status 集合:', statusArray)

  // 确定要传递的status参数
  let statusParam: number[] | string | undefined
  if (queryParams.status && queryParams.status !== '') {
    // 如果选择了具体的tab，传递当前tab的status
    statusParam = queryParams.status
  } else {
    // 如果选择"全部"，传递status集合
    statusParam = statusArray
  }

  console.log('最终传递的status参数:', statusParam)

  try {
    if (isMy.value) {
      // 同时获取列表数据和状态统计
      const [listData] = await Promise.all([
        ProjectApi.getProjectMyPage({
          ...queryParams,
          materialClassId: queryParams.materialClassId, // 确保传递节点ID
          mysurvey: mysurvey.value, // 确保传递节点ID
          status: statusParam // 传递当前tab的status或status集合
        }),
        getMyStatusCount()
      ])
      list.value = listData.list
      total.value = listData.total
    } else {
      // 同时获取列表数据和状态统计
      const [listData] = await Promise.all([
        ProjectApi.getProjectPage({
          ...queryParams,
          status: statusParam, // 传递当前tab的status或status集合
          materialClassId: queryParams.materialClassId // 确保传递节点ID
        }),
        getStatusCount()
      ])
      list.value = listData.list
      total.value = listData.total
    }

    // 检查展开的行是否还在当前数据中
    validateExpandState()
  } finally {
    loading.value = false
  }
}

// 验证展开状态，清除不在当前数据中的展开行
const validateExpandState = () => {
  const currentRowIds = list.value.map((item) => String(item.id))
  const validExpandKeys = expandRowKeys.value.filter((key) => currentRowIds.includes(key))

  if (validExpandKeys.length !== expandRowKeys.value.length) {
    expandRowKeys.value = validExpandKeys
    saveExpandState()
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ProjectApi.deleteProject(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ProjectApi.exportProject(queryParams)
    download.excel(data, '项目.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 调查分配相关的代码 */
const assignFormRef = ref()
const openAssignForm = async (row: ProjectVO, type: 'survey' | 'sample') => {
  await ProjectApi.checkStatus(row.id, 10)
  assignFormRef.value.open(row, type)
}

const openSamplingForm = async (row: ProjectVO, type: 'survey' | 'sample') => {
  await ProjectApi.checkStatus(row.id, 50)
  assignFormRef.value.open(row, type)
}

/** Tab切换处理 */
const handleTabChange = (tabName: string) => {
  console.log('Tab切换处理:', tabName)
  queryParams.status = tabName
  queryParams.pageNo = 1
  getList()
}

/** 树节点点击事件处理 */
const handleTreeNodeClick = (nodeId: number) => {
  queryParams.materialClassId = nodeId
  queryParams.pageNo = 1
  getList()
}

/** 刷新列表 */
const refreshList = () => {
  getList()
}
//  提前判断进入页面的需要的状态 不满足无法跳转
const toPage = async (row: ProjectVO, path: string, status: number) => {
  await ProjectApi.checkStatus(row.id, status)
  if ('/survey/qualitativeCompletion' == path) {
    // 打开同步定性结果弹窗
    syncResultsDialogVisible.value = true
    projectId.value=row.id+''
    console.log('projectId.value',projectId.value)
  }else {
    await router.push({
      path: path,
      query: {
        projectId: row.id,
        projectNo: row.projectNo,
        tbflag: 'false'
      }
    })
  }
}

const expandRowKeys = ref<string[]>([])

// 展开状态持久化存储的key
const EXPAND_STATE_KEY = 'project_list_expand_state'

// 从本地存储恢复展开状态
const restoreExpandState = () => {
  try {
    const savedState = localStorage.getItem(EXPAND_STATE_KEY)
    if (savedState) {
      const parsedState = JSON.parse(savedState)
      if (Array.isArray(parsedState)) {
        expandRowKeys.value = parsedState
      }
    }
  } catch (error) {
    console.warn('恢复展开状态失败:', error)
  }
}

// 保存展开状态到本地存储
const saveExpandState = () => {
  try {
    localStorage.setItem(EXPAND_STATE_KEY, JSON.stringify(expandRowKeys.value))
  } catch (error) {
    console.warn('保存展开状态失败:', error)
  }
}

const handleRowClick = (row: ProjectVO) => {
  const rowId = String(row.id)
  if (expandRowKeys.value[0] === rowId) {
    expandRowKeys.value = []
  } else {
    expandRowKeys.value = [rowId]
  }
  // 保存展开状态
  saveExpandState()
}

// 解析路径范围，支持格式：tobesurvery/all/2/9
const parsePathRange = (path) => {
  const parts = path.split('/')
  // 判断第三个路径部分是否为 "my"
  isMy.value = parts.length >= 3 && (parts[3] === 'my')||parts.length >= 3 && (parts[3] === 'mysample')
  isAll.value = parts.length >= 3 && parts[3] === 'all'
  console.log('isAll:', isAll.value, '第三个部分:', parts[3])
  console.log('isMy:', isMy.value, '第三个部分:', parts[3])
  console.log('解析路径:', path, '分割后:', parts)

  // 检查路径格式：/survey/mysurvey/my/2/9 (至少6个部分)
  if (parts.length < 6) {
    console.log('路径格式不正确，长度不足')
    tabRangeArr.value = []
    return
  }

  // 获取数字部分（索引4和5，即最后两个部分）
  const startStr = parts[4]
  const endStr = parts[5]

  console.log('起始数字部分:', startStr, '结束数字部分:', endStr)

  // 检查是否为数字
  const start = parseInt(startStr, 10)
  const end = parseInt(endStr, 10)

  if (isNaN(start) || isNaN(end)) {
    console.log('第三个或第四个部分不是数字')
    tabRangeArr.value = []
    return
  }

  // 检查范围是否有效
  if (start > end) {
    console.log('起始数字大于结束数字，无效范围')
    tabRangeArr.value = []
    return
  }

  // 生成范围数组
  const rangeArray = Array.from({ length: end - start + 1 }, (_, i) => start + i)
  console.log('生成的范围数组:', rangeArray)

  tabRangeArr.value = rangeArray
}

/** 初始化 **/
onMounted(() => {
  // 恢复展开状态
  restoreExpandState()

  // 分割路径
  const fullPath = route.fullPath
  console.log('fullPath:', fullPath)
  mysurvey.value = fullPath
  parsePathRange(fullPath)
  getList()
})
</script>

<style lang="scss" scoped>
:deep(.el-tabs__nav) {
  padding: 0 10px;
}

:deep(.el-tabs__item) {
  padding: 0 9px !important;
  height: 32px;
  line-height: 32px;
  font-size: 13px;
  color: var(--el-text-color-regular);
  transition: all 0.3s;
  position: relative;

  // 添加竖线分隔符
  &:not(:last-child)::after {
    content: '';
    position: absolute;
    right: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 1px;
    height: 14px;
    background-color: var(--el-border-color-lighter);
  }

  &.is-active {
    color: var(--el-color-primary);
    font-weight: 500;
  }

  &:hover {
    color: var(--el-color-primary);
  }
}

:deep(.el-tag) {
  margin-left: 4px;
  height: 18px;
  line-height: 18px;
  padding: 0 4px;
  border-radius: 9px;
  font-size: 13px;
  border: none;
  background-color: var(--el-color-info-light-9);

  .is-active & {
    background-color: var(--el-color-primary-light-9);
    color: var(--el-color-primary);
  }
}

:deep(.el-tabs__active-bar) {
  height: 2px;
  border-radius: 1px;
}

// 调整布局样式
.flex {
  display: flex;
}

.h-\[calc\(100vh-100px\)\] {
  height: calc(100vh - 100px);
}

.tree-container {
  position: relative;
  width: 200px;
}

.flex-1 {
  flex: 1;
}

.overflow-hidden {
  overflow: hidden;
}

.pl-4 {
  padding-left: 16px;
}

.pr-4 {
  padding-right: 16px;
}

.border-r {
  border-right-width: 1px;
}

.border-solid {
  border-style: solid;
}

.border-\[var\(--el-border-color-light\)\] {
  border-color: var(--el-border-color-light);
}

.flex-col {
  flex-direction: column;
}

:deep(.el-table) {
  height: 100%; // 让表格高度填充剩余空间
}

:deep(.el-table__body-wrapper) {
  overflow-y: auto; // 表格内容可滚动
}

.mt-4 {
  margin-top: 16px;
}

.h-full {
  height: 100%;
}

.mb-4 {
  margin-bottom: 16px;
}

:deep(.el-scrollbar__wrap) {
  overflow-x: hidden;
}

:deep(.el-scrollbar__bar.is-horizontal) {
  display: none;
}

/* 字典标签样式 */
:deep(.el-table) {
  .dict-tag.el-tag {
    display: inline-flex !important;
    align-items: center !important;
    justify-content: center !important;
    height: 24px !important;
    padding: 0 8px !important;
    font-size: 13px !important;
    border-radius: 4px !important;
    margin: 0 !important;

    /* 状态标签样式 */
    &.el-tag--primary {
      color: var(--el-color-primary) !important;
      background-color: var(--el-color-primary-light-9) !important;
      border-color: var(--el-color-primary-light-5) !important;
    }

    &.el-tag--success {
      color: var(--el-color-success) !important;
      background-color: var(--el-color-success-light-9) !important;
      border-color: var(--el-color-success-light-5) !important;
    }

    &.el-tag--warning {
      color: var(--el-color-warning) !important;
      background-color: var(--el-color-warning-light-9) !important;
      border-color: var(--el-color-warning-light-5) !important;
    }

    &.el-tag--danger {
      color: var(--el-color-danger) !important;
      background-color: var(--el-color-danger-light-9) !important;
      border-color: var(--el-color-danger-light-5) !important;
    }

    &.el-tag--info {
      color: var(--el-color-info) !important;
      background-color: var(--el-color-info-light-9) !important;
      border-color: var(--el-color-info-light-5) !important;
    }
  }
}

/* 展开行样式 */
.expand-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding-left: 70px;
  background-color: var(--el-fill-color-light);

  :deep(.el-button) {
    font-size: 13px;
    margin: 0;
  }

  /* 当前状态按钮的下划线样式 */
  :deep(.current-status-button) {
    position: relative;
    font-weight: 600 !important;
    color: var(--el-color-primary) !important;

    &::after {
      content: '';
      position: absolute;
      bottom: -4px;
      left: 0;
      right: 0;
      width: 100%;
      height: 3px;
      background-color: var(--el-color-primary);
      border-radius: 2px;
      box-shadow: 0 1px 3px rgba(64, 158, 255, 0.3);
    }
  }
}

.collapse-btn,
.expand-btn {
  border-radius: 0 !important;
  box-shadow: none !important;
  border: none;

  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
}

.collapse-btn {
  position: absolute;
  top: 320px;
  z-index: 10;
}

.expand-btn {
  position: absolute;
  left: 0;
  top: 320px;
  z-index: 10;
}
</style>
